import { TerrainConfig } from './config/MapConfig';
import { TerrainConfigItem, TerrainConfigManager } from './utils/TerrainConfigManager';

export class TerrainList extends Laya.Box {
    private terrainItems: Array<TerrainConfigItem> = [];
    private list: Laya.List;

    constructor() {
        super();
        this.initList();
        this.loadTerrainConfig();
    }

    private initList() {
        this.list = new Laya.List();
        this.list.itemRender = TerrainItem;
        this.list.repeatX = 1;
        this.list.repeatY = 0;
        this.list.width = 500;
        this.list.height = 2000;
        this.list.vScrollBarSkin = "skin/scrollbar/scrollbar_1.png";
        this.list.selectEnable = true;
        this.list.selectHandler = new Laya.Handler(this, this.onItemSelect);
        this.addChild(this.list);
        this.size(500, 2000);
        this.bgColor = '#ffffff';
    }

    private async loadTerrainConfig() {
        try {
            // const response = await fetch('configs/Terrain/TerrainConfigs.json');
            const config = TerrainConfigManager.getInstance().getTerrainList()//await response.json();

            // 使用 terrains 数组并添加 type 字段（根据 id 前缀判断类型）
            this.terrainItems = config.map((item: TerrainConfigItem) => ({

                id: item.id,
                icon: TerrainConfigManager.getInstance().getFullResourcePath(item.icon),  // 使用完整的资源路径
                type: item.type,   // 使用 id 的第一位作为 type
                name: item.name   // 使用 id 的第一位作为 type
            }));

            this.list.array = this.terrainItems;
        } catch (error) {
            console.error('Failed to load terrain config:', error);
        }
    }

    private onItemSelect(index: number): void {
        if (index !== -1) {
            const item = this.terrainItems[index];
            this.event('terrainSelected', [item.type, item.id, item.icon]);
            this.list.selectedIndex = -1;
        }
    }
}

class TerrainItem extends Laya.Box {
    constructor() {
        super();
        // 初始高度固定为600，宽度将根据图片动态调整
        this.height = 600;
        this.bgColor = '#ffffff';
        this.width = 600;
    }
    private icon: Laya.Image
    set dataSource(data: any) {
        if (!data) return;
        // if (this.icon) return;
        this.removeChildren();

        const icon = new Laya.Image();
        this.icon = icon
        icon.skin = data.icon;

        // 设置图片加载完成后的回调
        icon.on(Laya.Event.LOADED, this, () => {
            this.setSize()
        });

        this.addChild(icon);

        const label = new Laya.Label();
        label.text = data.id + "_" + data.name;
        label.fontSize = 45;
        label.color = '#000000';
        label.name = "itemLabel"; // 添加名称以便后续引用
        label.pos(65, 520); // 初始位置，将在图片加载后调整
        this.addChild(label);
        this.setSize()
    }
    setSize() {
        let icon = this.icon
        // 计算等比例缩放后的宽度
        if (icon.width == 0) return
        const scale = 500 / icon.width;
        const scaledheight = icon.height * scale;

        // 设置图片尺寸
        icon.width = 500;
        icon.height = scaledheight;

        // 设置容器宽度与图片一致
        this.height = scaledheight;

        // 居中显示图片
        icon.pos(0, 0);

        // 调整标签位置
        const label = this.getChildByName("itemLabel") as Laya.Label;
        if (label) {
            label.pos(scaledheight / 2 - label.width / 2, 520);
        }
    }
}
